const { Wechaty, Room } = require('wechaty') // import { Wechaty } from 'wechaty'
const qrcode = require('qrcode-terminal')
const { getForecast } = require('./superagent/hefeng')
const { sendMail } = require('./mailer/index')
const { schedule, tipText } = require('./utils/index')
const { PuppetPadplus } = require("wechaty-puppet-padplus") // padplus协议包
const config = require('./config/index')

const token = config.padplus_key
const puppet = new PuppetPadplus({
  token,
})

const bot = new Wechaty({
  puppet
})
// const bot = new Wechaty()

/** 查询天气类型 */
const date_types = {
  tod: 'today',
  tom: 'tommorrow',
  tdat: 'tdat'
}

/** 每小时 */
const STONE_TIME = '0 0 * * * ?'
/** 每天18:20:00 */
const TOWARD_EVENING = '0 20 18 * * ?'
/** 每天07:10:00 */
const MORNING = '0 10 7 * * ?'

/** 微信bot */
bot.on('scan', (wx_qrcode, status) => {
  qrcode.generate(wx_qrcode, { small: true })
  console.log('status：', status)
})
bot.on('login', user => {
  console.log(`${user}已登录\n`)
  sendMail({ subject: `${user}登录提醒`, content: `您的微信账号${user}已在后台服务登录成功` })

  // _getForecast(0)
  _getForecast(1)
  // _getForecast(2)

  /** 定时任务 */
  schedule(MORNING).then(() => {
    _getForecast(0)
  })
  schedule(TOWARD_EVENING).then(() => {
    _getForecast(1)
  })
})
bot.on('logout', user => {
  console.log(`${user}已退出登录\n`)
  sendMail({ subject: `退出登录提醒`, content: `您的微信账号${user}已在后台服务退出` })
})
bot.start()

function _getForecast (type) {
  getForecast().then(async res => {
    let room = await bot.Room.find({ topic: 'sky' })
    let room_3 = await bot.Room.find({ topic: '有酒有故事的地方' })
    // let room_2 = await bot.Room.find({ topic: '动物世界' })

    let { HeWeather6: [{ daily_forecast }] } = res
    let message = tipText(type, daily_forecast[type])

    // const msg2 = await room.say('Hello world!')
    // const msg3 = await room_3.say('Hello world!')
    if (parseInt(daily_forecast[type]['cond_code_d']) >= 300 && parseInt(daily_forecast[type]['cond_code_d']) < 500) {
      try {
        const msg = await room.say(message) // only supported by puppet-padplus
        // room_2.say(message)
        sendMail({ subject: '降雨提醒！', content: message })
        // console.log(msg)
      } catch (error) {
        sendMail({ subject: '降雨提醒！', content: message })
      }
    }
  })
}

// 来源：
// https://github.com/wechaty/wechaty
// https://github.com/isboyjc/wechaty-Robot
// https://github.com/gengchen528/wechatBot
// https://wechaty.js.org/v/zh/puppet

/**
 * Send text,media file, contact card, or text with mention @mention contact inside Room,
 * return the message which the bot sent (only puppet-padplus supported).
 *
 * await room.say('Hello world!')
 * const msg = await room.say('Hello world!') // only supported by puppet-padplus
 *
 * puppet-padplus 对第一次登录前已有的群发消息失败，第一次登录后新建的群发消息成功
 * 最新：对汉字群名发送消息失败（又好了）
 *
 * https://www.jianshu.com/p/f5f1f4d64483(forever管理node服务)
 */
